<template>
  <div>
    <!-- 文章标题 -->
    <div class="block">文章标题</div>
    <div style="margin-bottom: 15px">
      <el-input v-model="form.title" placeholder="请输入文章标题"></el-input>
    </div>

    <!-- 文章编辑 -->
    <div class="block">
      文章编辑
      <!-- <button v-if="mode === 'edit' && ismdFlag == false" @click="changeCont">
        转html为md
      </button> -->
    </div>
    <mavon-editor
      ref="toastuiEditor"
      placeholder="请输入文档内容..."
      :boxShadow="false"
      style="z-index: 1; border: 1px solid #d9d9d9; height: 50vh"
      v-model="content"
      @imgAdd="$imgAdd"
      :toolbars="toolbars"
      @save="saveMavon"
      @change="changeMavon"
    ></mavon-editor>
    <!-- 文章描述 -->
    <div class="block">文章描述</div>
    <el-input type="textarea" v-model="form.description" :rows="6"></el-input>

    <!-- 文章头图 -->
    <Upload uploadTitle="文章头图" v-model="form.thumb" />

    <!-- 选择分类 -->
    <div class="block">选择分类</div>
    <el-select
      v-model="form.blogCategoryId"
      slot="prepend"
      placeholder="请选择文章分类"
      @change="change"
    >
      <el-option
        v-for="item in blogType"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      ></el-option>
    </el-select>
    <div>
      <!-- 发布按钮 -->
      <el-button
        type="primary"
        style="margin-top: 15px"
        @click="addArticleHandle"
        >{{ btnContent }}</el-button
      >
    </div>
  </div>
</template>

<script>
import OSS from "ali-oss";
//
import { mavonEditor } from "mavon-editor";
import "mavon-editor/dist/css/index.css";
import axios from "axios";

// ↑
import Upload from "@/components/Upload.vue";
import { getBlogType } from "@/api/blogType.js";
import { addBlog, editBlog, findOneBlog } from "@/api/blog.js";
import { getUser } from "@/utils/auth.js";
import { checkStatus } from "@/api/checkStatus.js";

export default {
  props: ["mode"],
  data() {
    return {
      ismdFlag: false,
      content: "", // 文本域的值
      html: "", //
      markdown: "", //左侧 markdown 内容
      toolbars: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: false, // 保存（触发events中的save事件）
        ishljs: false, //代码高亮
        // codeStyle:'agate',
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式
        preview: true, // 预览
      },

      // ↑
      author: null,
      id: null,
      form: {
        authorId: "",
        blogCategoryId: "",
        title: "",
        description: "",
        thumb: "",
        htmlContent: "",
        markdownContent: "",
      },
      blogType: [], // 存放博客分类
      imageUrl: "", // 图片在服务器上面的地址
      // editorOptions: {
      //   language: "zh-CN",
      // },
      btnContent: "发布文章",
      obj: {},
    };
  },
  created() {
    checkStatus().then((res)=>{
      console.log(res,"status");
    })
    // 一进来的时候，就需要拿取分类的数据
    getBlogType().then(({ data }) => {
      // console.log(data["records"]);
      if (data["records"]) {
        this.blogType = data["records"];
      } else {
        console.log("出错了");
      }
    });
    if (this.mode === "edit") {
      // 一进来的时候，就拿到传递过来的 id，根据这个 id 获取到这篇文章的内容，回填到表单
      this.id = this.$route.params.id;
      findOneBlog(this.id).then((res) => {
        console.log(res);
        // console.log(data, "sf");
        // 接下来，将这个内容回填至表单
        this.form = res.data;
        this.content = res.data.markdownContent;
        this.form.blogCategoryId =
          res.data.blogCategory === null ? "" : res.data.blogCategory.id;
        // this.$refs.toastuiEditor.invoke("setHTML", data.htmlContent);
        this.content = res.data.markdownContent;
        this.author = this.form.author.id;
      });
      this.btnContent = "确认修改";
    }
  },
  components: {
    // editor: Editor,
    Upload,
    mavonEditor,
  },
  mounted() {
    let user = getUser();
    // console.log(user.id);
    this.author = user;
    // console.log(this.author);
  },
  methods: {
    //输入框事件
    changeMavon() {
      this.html = this.$refs.toastuiEditor.d_render;
      console.log(this.html);
      this.markdown = this.$refs.toastuiEditor.d_value;
      // console.log(this.markdown);
    },
    //获取html md 文档
    saveMavon(value, render) {
      sessionStorage.setItem("article", value);
    },
    // 上传图片方法
    async $imgAdd(pos, $file) {
      const client = new OSS({
        accessKeyId: "LTAI5tG5NbpvLQxhM5W1B9ys",
        accessKeySecret: "vJGnTSThKsLiYPRS9v6jyk3v99Mp8u",
        bucket: "join-blog",
        region: "oss-cn-beijing",
      });
      try {
        const ossRes = await client.put(
          new Date().getTime() + $file.name,
          $file
        );
        if (ossRes.res.status === 200) {
          console.log(ossRes.res.requestUrls);
          this.$refs.toastuiEditor.$img2Url(pos, ossRes.res.requestUrls);
          // return tokenInfo.fileId;
        } else {
          console.error("oss上传失败");
        }
      } catch (e) {
        console.log(
          "%c 🍠 e: ",
          "font-size:20px;background-color: #2EAFB0;color:#fff;",
          e
        );
      }
    },

    // ↑
    addArticleHandle() {
      // console.log(this.form);

      // 接下来，我们来组装要传递给服务器的对象
      this.obj = {
        authorId: this.author.userId,
        title: this.form.title,
        description: this.form.description || "",
        createDate: new Date().getTime(),
        blogCategoryId: this.form.blogCategoryId,
        htmlContent: this.html,
        thumb: this.form.thumb,
        markdownContent: this.markdown,
      };
      console.log(this.obj, "author");
      // 对象组装好以后，就提交给服务器
      if (
        this.obj.authorId &&
        this.obj.title &&
        this.obj.markdownContent &&
        this.obj.htmlContent &&
        this.obj.blogCategoryId
      ) {
        if (this.mode === "add") {
          // 说明是要新增
          addBlog(this.obj).then((res) => {
            console.log(res);
            this.$message({
              type: "success",
              message: res.message,
            });
            this.$router.push("/blogList"); // 跳转到文章列表
          });
        } else {
          // 说明是要编辑
          let obj = {
            id: this.id,
            authorId: this.form.author.id,
            title: this.form.title,
            description: this.form.description,
            createDate: new Date().getTime(),
            blogCategoryId: this.form.blogCategoryId,
            htmlContent: this.html,
            thumb: this.form.thumb,
            markdownContent: this.markdown,
          };
          console.log();
          editBlog(obj).then((res) => {
            console.log(res, "mad");
            this.$router.push("/blogList"); // 跳转到文章列表
            if (res.code == 200) {
              this.$message.success("文章修改成功");
            }
          });
        }
      } else {
        this.$message.error("请填写所有内容");
      }
    },
    change() {
      this.$forceUpdate();
    },
  },
};
</script>

<style lang="scss" scoped>
.markdown-body {
  // width: 94%;
  height: 600px !important;
  // margin-left: 6% !important;
}
.block {
  margin: 15px 0;
  font-weight: 100;
}
</style>